<template>
  <div>
    <Header />
    <div>
      <van-form @submit="onSubmit">
        <van-field v-model="phone"
                   name="phone"
                   label="手机号"
                   placeholder="手机号"
                   :rules="[{ required: true, message: '请填写手机号' }]" />
        <van-field v-model="password"
                   type="password"
                   name="password"
                   label="密码"
                   placeholder="密码"
                   :rules="[{ required: true, message: '请填写密码' }]" />
        <div style="margin: 16px;">
          <van-button round
                      block
                      type="info"
                      native-type="submit">
            登陆
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import Header from './components/HeaderLogin'
export default {
  name: 'Login',
  components: {
    Header
  },
  data() {
    return {
      phone: '13919618048',
      password: '123456',
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  methods: {
    onSubmit(data) {
      this.$store.dispatch('user/login', data)
        .then(() => {
          this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
        })
        .catch(() => {
        })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }

}
</script>

<style>
</style>
